package com.ambulance.project.biz.controller.bigweb;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ambulance.common.exception.CustomException;
import com.ambulance.common.utils.ServletUtils;
import com.ambulance.common.utils.file.FileUploadUtils;
import com.ambulance.framework.config.MySystemConfig;
import com.ambulance.framework.security.LoginUser;
import com.ambulance.framework.security.service.TokenService;
import com.ambulance.framework.task.HdTask;
import com.ambulance.framework.web.domain.AjaxResult;
import com.ambulance.project.biz.dto.DispatchDto;
import com.ambulance.project.biz.dto.pad.PatientInfo;
import com.ambulance.project.biz.dto.web.CarHDInfo;
import com.ambulance.project.biz.dto.web.WebCarDto;
import com.ambulance.project.biz.entity.CarChannel;
import com.ambulance.project.biz.entity.Dispatch;
import com.ambulance.project.biz.entity.DispatchCase;
import com.ambulance.project.biz.entity.Patient;
import com.ambulance.project.biz.service.*;
import com.ambulance.project.biz.util.BASE64DecodedMultipartFile;
import com.ambulance.project.manager.domain.BizCardevice;
import com.ambulance.project.manager.service.IBizCardeviceService;
import com.ambulance.project.system.domain.SysUser;
import com.ambulance.utils.CommonUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
 * @Author RXL
 * @Date 2020/4/29 10:44
 * @Version 1.0
 */
@Controller
@Api(tags = "可视化-首页信息")
@RequestMapping(value = "/web/v1/base", method = RequestMethod.POST)
public class BaseInfoController {


    @Autowired
    private MyCustomerService myCustomerService;
    //
    @Autowired
    private TokenService tokenService;

    @Autowired
    private PatientService patientService;
    @Autowired
    private CarService carService;
    @Autowired
    private HdTask hdTask;
    @Autowired
    private CarDeviceService carDeviceService;
    @Autowired
    private IBizCardeviceService iBizCardeviceService;
    @Autowired
    private DispatchCaseService dispatchCaseService;

    /**
     * @Description： base64字符串转化成图片
     * @param: imgStr
     * @Return:
     */
    public static String GenerateImage(String base64Data) {
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据

        String[] d = base64Data.split("base64,");//将字符串分成数组
        if (d != null && d.length == 2) {
            dataPrix = d[0];
            data = d[1];
        }

        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        }

        try {
            String[] baseStrs = data.split(",");

//            Encoder encoder = Base64.getEncoder();
//            String result = encoder.encodeToString(byteArray);
// 
//            Decoder decoder = Base64.getDecoder();
//            byte[] result = decoder.decode(str);

            Base64.Decoder decoder = Base64.getDecoder();
            byte[] b = new byte[0];
            b = decoder.decode(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            MultipartFile multipartFile = new BASE64DecodedMultipartFile(b, dataPrix);
            String upload = FileUploadUtils.upload(MySystemConfig.getUploadPath(), multipartFile);
            return upload;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    @ApiOperation(value = "车辆列表", notes = "首页信息", produces = "application/json")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = WebCarDto.class, message = "响应")
    })
    @RequestMapping(value = "/cars")
    @ResponseBody
    public Object cars(
    ) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        return AjaxResult.success(myCustomerService.listCar(user.getUserId()));
    }

    @ApiOperation(value = "质控管理", notes = "车辆质控管理", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carID", value = "车辆标识", dataType = "string"),

    })
    @ApiResponses({
            @ApiResponse(code = 200, response = DispatchDto.class, message = "响应")
    })
    @RequestMapping(value = "/dispatchInfo")
    @ResponseBody
    public Object dispatchInfo(
            @RequestParam(value = "carID") Integer carID
    ) {

        Dispatch dispatch = myCustomerService.getRecentDispatchByCarID(carID);
        DispatchDto dispatchDto = DispatchDto.copyFromBean(dispatch);
        return AjaxResult.success(dispatchDto);
    }

    @ApiOperation(value = "患者信息", notes = "患者信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carID", value = "车辆标识", dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = PatientInfo.class, message = "响应")
    })
    @RequestMapping(value = "/patientMsg")
    @ResponseBody
    public Object patientMsg(
            @RequestParam(value = "carID") Integer carID
    ) {
        DispatchCase dispatchCase = myCustomerService.getDispatchCaseRecentByCar(carID);
        if (CommonUtils.checkNull(dispatchCase)) {
            throw new ClassCastException("未查到相关信息");
        }
        Patient patient = patientService.getById(dispatchCase.getPatientId());
        PatientInfo info = PatientInfo.fromPatient(patient);
        info.setUserName(dispatchCase.getPatientName());
        info.setUserPhone(dispatchCase.getPatientMobile());
        info.setUserAddress(dispatchCase.getPatientAddress());
        info.setMajorCase(dispatchCase.getMajorCase());
        if (!CommonUtils.checkNull(dispatchCase.getCheckResult())) {
            info.setCheckResult(dispatchCase.getCheckResult());
        }
        info.setCarVin(dispatchCase.getVin());
        info.setHospital(dispatchCase.getHospital());
        info.setPatientLocal(dispatchCase.getPatientLocal());
        info.setAge(dispatchCase.getPatientAge());
        info.setSex(dispatchCase.getPatientSex());
        info.setMedicineSensitive(dispatchCase.getMedicineSensitive());
        info.setCarID(Integer.valueOf(carID));
        return AjaxResult.success(info);
    }

    /**
     * 查询车辆视频
     *
     * @return
     */
    @ApiOperation(value = "车辆视频监控流", notes = "车辆视频监控流", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carID", value = "车辆标识", dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = CarChannel.class, message = "响应")
    })
    @RequestMapping(value = "/car/video")
    @ResponseBody
    public Object carVideo(@RequestParam(value = "carID") Integer carID) {
        return AjaxResult.success(carService.getCarChannel(carID));
    }

    @ApiOperation(value = "车辆报警信息", notes = "车辆报警信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carID", value = "车辆标识", dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = CarHDInfo.class, message = "响应")
    })
    @RequestMapping(value = "/car/alert")
    @ResponseBody
    public Object carAlert(@RequestParam(value = "carID") Integer carID) {
        CarHDInfo carGpsInfo = hdTask.getCarGpsInfo(carService.getById(carID).getId().toString(), carService.getById(carID).getVin());
        return AjaxResult.success(carGpsInfo);
    }

    @ApiOperation(value = "车载设备信息", notes = "车载设备信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carID", value = "车辆标识", dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = BizCardevice.class, message = "响应")
    })
    @RequestMapping(value = "/car/deviceinfo")
    @ResponseBody
    public Object carDeviceAlert(@RequestParam(value = "carID") Integer carID) {
        final BizCardevice bizCardevice = new BizCardevice();
        bizCardevice.setCarID(carID.longValue());
        final List<BizCardevice> bizCardevices = iBizCardeviceService.selectBizCardeviceList(bizCardevice);
        if (CommonUtils.checkNull(bizCardevices)) {
            throw new CustomException("该车暂未绑定任何车载设备");
        }
        return AjaxResult.success(bizCardevices);
    }

    @ApiOperation(value = "上传设备截图", notes = "上传设备截图", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dispatchID", value = "调度编号", dataType = "string"),
            @ApiImplicitParam(name = "image", value = "图片", dataType = "string"),
            @ApiImplicitParam(name = "type", value = "类型 1=心电,2=呼吸机", dataType = "int"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResult.class, message = "响应")
    })
    @RequestMapping(value = "/deviceImage")
    @ResponseBody
    public AjaxResult getEcgImage(@RequestParam(value = "dispatchID") Integer dispatchID,
                                  @RequestParam(value = "image") String image,
                                  @RequestParam(value = "type") Integer type
    ) {
        final QueryWrapper<DispatchCase> dispatchCaseQueryWrapper = new QueryWrapper<DispatchCase>().eq("dispatchID", dispatchID);
        final DispatchCase dispatchCase = dispatchCaseService.getOne(dispatchCaseQueryWrapper);
        if (!ObjectUtil.isNull(dispatchCase)) {
            final String generateImage = GenerateImage(image);
            if (type == 1) {
               //心电
                final String newJoin = checkStringLength(dispatchCase.getEcgImage(), generateImage);
                dispatchCase.setEcgImage(newJoin);
            } else if (type == 2) {
                final String newJoin = checkStringLength(dispatchCase.getBrImage(), generateImage);
                dispatchCase.setBrImage(newJoin);
            }
        }
        final boolean dispatchID1 = dispatchCaseService.update(dispatchCase, dispatchCaseQueryWrapper);
        return AjaxResult.AutoResponse(dispatchID1);
    }

    private String checkStringLength(String str,String generateImage){
        String[] split = StrUtil.split(str, ",");
        if(split.length >= 5){
            split = ArrayUtil.remove(split, 0);
        }
        final String[] append = ArrayUtil.append(split, generateImage);
        final String join = ArrayUtil.join(append, ",");
        return join;
    }
}





















